package org.xiaoyu.rpc.remoting.transport.cllient;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;
import org.xiaoyu.rpc.remoting.packet.HeartbeatRequest;

import java.util.concurrent.TimeUnit;

/**
 * Created By Have
 * 2021/7/21 20:30
 */
@Slf4j
public class ClientHeartbeatHandler extends ChannelInboundHandlerAdapter {
    private static final int HEARTBEAT_INTERVAL = 5;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        schedulerSendHeartbeat(ctx);
        super.channelActive(ctx);
    }

    private void schedulerSendHeartbeat(ChannelHandlerContext ctx) {
        ctx.executor().schedule(() -> {
            if (ctx.channel().isActive()) {
                if (log.isDebugEnabled()) {
                    log.debug("Just send heartbeat");
                }
                ctx.writeAndFlush(new HeartbeatRequest());
                schedulerSendHeartbeat(ctx);
            }
        }, HEARTBEAT_INTERVAL, TimeUnit.SECONDS);

    }
}
